import { h } from 'vue';
import { ElFormItem, ElInput } from 'element-plus';
import { definePlugin } from '@/components/@comp/create-component';
import columnsHelper from '@/components/@comp/columns-helper';

const defaultStatus = ['disabled', 'readonly'];

function ReadValue({ value, render }) {
  return render?.(value) || value;
}

const FormatColumns = {
  type: 'item',
  run(item) {
    return {
      ...item,
      key: item.key || item.name || item.dataIndex,
      name: item.name || item.dataIndex,
    };
  },
};

const GetFormItems = {
  type: 'item',
  run(item, options) {
    const { formModel, name, viewType, formItemState } = options;

    // 表单关联事件产生的状态数据
    // const itemState = formItemState[item.name] || {};

    // const itemViewType =
    //   itemState.viewType || defaultStatus.includes(viewType) ? viewType : item.viewType?.[name] || item.viewType;

    // if (itemViewType === 'hidden' || itemState.hidden === true) return null;

    // const readonly = itemViewType === 'readonly' || itemState.readonly === true;

    return {
      ...item,
      // colSpan: itemState.colSpan || item.colSpan,
      // rowSpan: itemState.rowSpan || item.rowSpan,
      element: () =>
        h(
          ElFormItem,
          {
            label: item.title,
            ...item.itemProps,
            prop: item.name,
            key: item.key,
            rules: void 0,
          },
          {
            default: () =>
              h(item.input || ElInput, {
                ...item.inputNodeProps,
                modelValue: formModel[item.name],
                'onUpdate:modelValue': (value) => {
                  // console.log('input-value::', value);
                  formModel[item.name] = value;
                },
              }),
          },
        ),
    };
  },
};

const FormTransformColumns = definePlugin({
  name: 'FormTransformColumns',
  priority: 'CONTENT',
  collection: () => ({ transformExtension: [], formItemState: {} }),
  props: {
    type: String,
    model: Object,
    column: Number,
    columns: Array,
    viewType: null,
    columnsTransformConfig: null,
  },
  main(instance, props) {
    const { type, model, column, columns = [], viewType, columnsTransformConfig = {} } = props;

    const formColumns = columnsHelper.useColumns(columns, {
      // eventMap: {},
      ...columnsTransformConfig,
      name: type,
      enable: {
        sort: true,
        cover: true,
        form: true,
        formRules: true,
        format: true,
        render: true,
      },
      formState: {},
      column,
      viewType,
      formModel: model || {},
      formItemState: instance.collection.formItemState,
      afterExtension: [
        FormatColumns,
        ...(columnsTransformConfig.transformExtension || []),
        ...instance.collection.transformExtension,
        GetFormItems,
      ],
    });

    return {
      formColumns,
    };
  },
});

export default FormTransformColumns;
